package com.exercise;

/**
 * Created with IntelliJ IDEA.
 * Description:排序两个有序链表
 * User: YJ
 * Date: 2023-11-16
 * Time: 17:29
 */
public class Exercise1 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(5);
        ListNode l2 = new ListNode(3,l1);
        ListNode l3 = new ListNode(1,l2);

        ListNode l4 = new ListNode(5);
        ListNode l5 = new ListNode(3,l4);
        ListNode l6 = new ListNode(1,l5);
        ListNode merge = Merge(l3, l6);
        PrintList printList = new PrintList();
        printList.printList(merge);

    }

    public static ListNode Merge (ListNode pHead1, ListNode pHead2) {
        // write code here
        if (pHead1 == null && pHead2 == null) {
            return null;
        }
        if(pHead1 == null) {
            return pHead2;
        }
        if(pHead2 == null) {
            return pHead1;
        }
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        ListNode prev = new ListNode(-1);
        ListNode p = prev;

        while(p1 != null || p2 != null) {
            if (p1 == null) {
                p.next = p2;
                break;
            }
            if (p2 == null) {
                p.next = p1;
                break;
            }
            if (p1.val <= p2.val) {
                p.next = p1;
                p1 = p1.next;
                p = p.next;
                continue;
            }
            if (p2.val <= p1.val) {
                p.next = p2;
                p2 = p2.next;
                p = p.next;
                continue;
            }
        }
        return prev.next;
    }
}
